/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年03月27日
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
================================================================*/


#include <iostream>
#include <vector>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if( head == NULL ){
            return NULL;
        }
        
        vector<int> num;

        ListNode *p = head;
        while( p ){
            num.append(p->val);
            p = p->next;
        }

        int start = 0;
        int end = num.size()-1;

        return buildBST(num, start, end);
    }

private:
    TreeNode* buildBST(vector<int> &num, int start, int end){
        if( start > end )
            return NULL;

        int mid = (end - start)/2 + start;
        TreeNode* root = new TreeNode(num[mid]);
        root->left = buildBST(num, start, mid - 1);
        root->right = buildBST(num, mid+1, end);

        return root;
    }
};


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int size = 0;
    ListNode* node = NULL;

    TreeNode* sortedListToBST(ListNode* head) {
        if( head == NULL )
            return NULL;
        
        ListNode* p = head;
        node = head;
        while( p ){
            size++;
            p = p->next;
        }

        return buildBST(0, size-1);
    }

private:
    TreeNode* buildBST(int start, int end){
        if( start > end )
            return NULL;

        int mid = (end - start)/2 + start;
        TreeNode* left = buildBST(start, mid - 1);

        TreeNode* root = new TreeNode(node->val);
        root->left = left;
        
        node = node->next;

        TreeNode* right = buildBST(mid + 1, end);
        root->right = right;

        return root;
    }
};
